package com.ptu.util;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class CodeWebSocketHandler extends TextWebSocketHandler {

    // 保存手机号与WebSocketSession的映射关系
    private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    // 建立连接后
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("连接成功");
        String phone = session.getHandshakeHeaders().getFirst("phone"); // 获取手机号
        System.out.println("手机号：" + phone);
        if (phone != null) {
            sessions.put(phone, session);
        }
    }

    // 处理收到的消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 这里可以处理前端发来的消息
    }

    // 发送验证码
    public static void sendCode(String phone, String code) throws IOException {

        WebSocketSession session = sessions.get(phone);
        System.out.println("发送验证码：" + phone + " " + code);
        if (session != null && session.isOpen()) { // 如果WebSocket连接已打开
            session.sendMessage(new TextMessage(code));
        }
    }

    // 连接关闭后
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.values().removeIf(value -> value.getId().equals(session.getId()));
    }
}